//
//  MNDResetTransactionPwdViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/10.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDResetTransactionPwdViewController.h"
#import "NSString+ReplaceAsterisk.h"
#import "MNDWebViewController.h"
#import "UIButton+JKCountDown.h"

@interface MNDResetTransactionPwdViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userPhone;
@property (weak, nonatomic) IBOutlet UITextField *phoneCaptcha;

@property (copy, nonatomic) NSString *userPhoneNum;
@property (copy, nonatomic) NSString *captcha;

@end

@implementation MNDResetTransactionPwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    RAC(self, captcha) = self.phoneCaptcha.rac_textSignal;
    
    __block UITextField *captchaTextField = self.phoneCaptcha;
    [self.phoneCaptcha.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 6) {
            captchaTextField.text = [x substringToIndex:6];
        }
    }];
    
    __block UITextField *phoneTextField = self.userPhone;
    [self.userPhone.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 11) {
            phoneTextField.text = [x substringToIndex:11];
        }
    }];
    
    [self initialBackBarButtons];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadUserPhone];
}

- (void)initialBackBarButtons {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - Network

- (void)loadUserPhone {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_GET_PHONE parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            weakself.userPhoneNum = responseModel.data;
            weakself.userPhone.text = [weakself.userPhoneNum replaceWithAsteriskAtRange:NSMakeRange(3, 4)];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself popToPreVC];
            });
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)sendPhoneCaptcha:(UIButton *)sender {
    NSDictionary *params = @{@"user_phone": self.userPhoneNum, @"channel": @"app", @"srvtxcode": @"passwordResetPlus"};
    
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SEND_CAPTCHA parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:@"验证码已发送"];
            [sender jk_startTime:30 title:@"重新获取" waitTittle:@"秒后重发"];
            
        } else {
            NSDictionary *dic = responseModel.msg;
            [NetworkProgressHUD showHudMsg:dic[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)resetTransactionPwd {
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"smscode": self.captcha, @"channel": @"app"}];
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_DEPOSIT_RESET_PASSWORD parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
            webVC.webViewUrl = responseModel.data;
            webVC.loadType = LoadTypeHTMLString;
            webVC.title = @"设置交易密码";
            //这里必须用push
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)popToPreVC {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)sendPhoneCaptchaAction:(id)sender {
    if (self.userPhoneNum && self.userPhoneNum.length > 0) {
        [self sendPhoneCaptcha:sender];
    } 
}

- (IBAction)resetPasswordAction:(id)sender {
    if (self.captcha.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入验证码"];
        return;
    }
    
    [self resetTransactionPwd];
}

- (IBAction)dismissAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
